
const AudioPlayer = /** @class */ (function () {
  function AudioPlayer (muted, cb) {
    this.cacheBuffers = [] // 音频数据列表
    this.pauseTimer = null // 暂停定时器
    const AudioContext = window.AudioContext
    this.audioContext = new AudioContext()
    this.mediaSource = new MediaSource()
    this.audio = new Audio()
    this.audio.muted = muted
    this.audio.src = URL.createObjectURL(this.mediaSource)
    this.audioContextConnect()
    this.listenMedisSource()
    this.triggerStop = false
    this.cb = cb
  }
  // 停止播放
  AudioPlayer.prototype.stop = function () {
    this.cacheBuffers = [] // 音频数据列表
    this.audio.currentTime = this.sourceBuffer.timestampOffset
    clearTimeout(this.pauseTimer)
  }
  //  设置是否静音
  AudioPlayer.prototype.setMuted = function (v) {
    this.audio.muted = v
  }
  // 连接音频上下文
  AudioPlayer.prototype.audioContextConnect = function () {
    const source = this.audioContext.createMediaElementSource(this.audio)
    source.connect(this.audioContext.destination)
  }
  // 监听媒体资源
  AudioPlayer.prototype.listenMedisSource = function () {
    this.mediaSource.addEventListener('sourceopen', () => {
      if (this.sourceBuffer) return

      this.sourceBuffer = this.mediaSource.addSourceBuffer('audio/mpeg')

      this.sourceBuffer.addEventListener('update', () => {
        if (this.cacheBuffers.length && !this.sourceBuffer?.updating) {
          const cacheBuffer = this.cacheBuffers.shift()
          this.sourceBuffer?.appendBuffer(cacheBuffer)
        }

        this.pauseAudio()
      })
    })
  }
  // 暂停音频
  AudioPlayer.prototype.pauseAudio = function () {
    const neePlayTime = this.sourceBuffer.timestampOffset - this.audio.currentTime || 0

    this.pauseTimer && clearTimeout(this.pauseTimer)
    // 播放完成3秒后还没有新的音频流过来，则暂停音频播放
    this.pauseTimer = window.setTimeout(
      () => {
        this.audio.pause()
      },
      neePlayTime * 1000 + 3000
    )
  }
  AudioPlayer.prototype.playAudio = function () {
    // 为防止下一段音频流传输过来时，上一段音频已经播放完毕，造成音频卡顿现象，
    // 这里做了1秒的延时，可根据实际情况修正
    setTimeout(() => {
      if (this.audio.paused) {
        try {
          this.audio.play()
        } catch (e) {
          this.playAudio()
        }
      }
    }, 1000)
  }
  // 接收音频数据
  AudioPlayer.prototype.receiveAudioData = function (audioData) {
    if (!audioData.byteLength) return

    if (this.sourceBuffer?.updating) {
      this.cacheBuffers.push(audioData)
    } else {
      this.sourceBuffer?.appendBuffer(audioData)
    }

    this.playAudio()
  }
  return AudioPlayer
}())
export default AudioPlayer
